// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios')
const doubanbook = require('doubanbook')

cloud.init()

async function getBookData(isbn) {
  // https://search.douban.com/book/subject_search?search_text=9787115275790&cat=1001
  const url = `https://search.douban.com/book/subject_search?search_text=${isbn}&cat=1001`
  const res = await axios.get(url) 
  const reg = /window\.__DATA__ = "(.*)"/
  // console.log(res);
  if(reg.test(res.data)){
    let bookdata = RegExp.$1
    return doubanbook(bookdata)[0]
  }
  // console.log(res);
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database({
    env: 'cloud1-1g1zsdwp47d8aed1'
  })
  const { isbn } = event
  const bookdata = await getBookData(isbn)
  db.collection("books").add({
    data: {
      isbn: isbn,
      title: bookdata.title,
      cover_url: bookdata.cover_url
    }
  })
  return {
    title: bookdata.title,
    cover_url: bookdata.cover_url
  }
}